import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from cpswarehouse.lib.base import BaseController, render

log = logging.getLogger(__name__)

from cpswarehouse.lib.starquery import CpsStarQuery as StarQuery
from sqlalchemy import func

from cpswarehouse.model import YearDimension, SchoolDimension
from cpswarehouse.model.meta import Session

from pylons.decorators.cache import beaker_cache

from sqlalchemy import and_

import math

class IndexController(BaseController):

    @beaker_cache()
    def index(self):
        starquery = StarQuery()
        years = starquery.select_race(func=func.sum).\
            select_year().\
            select_school().\
            group_by_year().\
            fetch_all()

        c.years = list(years)

        c.schools = Session.query(SchoolDimension).filter(and_(SchoolDimension.latitude != None, SchoolDimension.longitude != None))
        return render('/index.mako')



    def results(self):
        return 
        schools = Session.query(SchoolDimension).filter(and_(SchoolDimension.latitude != None, SchoolDimension.longitude != None))
        results = []

        for school in schools:
            starquery = StarQuery()
            race_by_years = starquery.select_race(func=func.sum).\
                select_year().\
                select_school().\
                where_school_is(school.id).\
                group_by_year().\
                fetch_all()
            
            year_count = 0
            total = 0
            asian = 0
            black = 0
            hispanic = 0
            nativeamerican = 0
            white = 0

            for race_by_year in race_by_years:
                year_count += 1
                asian += race_by_year.asian
                black += race_by_year.black
                hispanic += race_by_year.hispanic
                nativeamerican += race_by_year.nativeamerican
                white += race_by_year.white
                total += (race_by_year.asian + race_by_year.black + race_by_year.hispanic + race_by_year.nativeamerican + race_by_year.white)
            
            total = float(total)/float(year_count)
            asian = float(asian)/float(year_count)
            black = float(black)/float(year_count)
            hispanic = float(hispanic)/float(year_count)
            nativeamerican = float(nativeamerican)/float(year_count)
            white = float(white)/float(year_count)                

            result_list = [school.school, school.latitude, school.longitude, total, asian, black, hispanic, nativeamerican, white]
            result_list = [str(x) for x in result_list]
            results.append(", ".join(result_list))

            
        return "\n".join(results)

# ASIAN_COLOR = '#0093BB'
# BLACK_COLOR = '#93B216'
# HISPANIC_COLOR = '#F5D600'
# NATIVEAMERICAN_COLOR = '#E8970A'
# WHITE_COLOR = '#683B1A'

